<?php

define( "SUPER_CACHE", false );

class ArrowCacheProvider extends ArrowObject{
	
	private static $removeWhiteSpace = false;
	
	public static function importModelsCache(){
		if(!SUPER_CACHE)
			return array();
		
	    if(isset($_GET["arrowDataRequest"])){
	    	$file =  ARROW_CACHE_PATH."/models_cache/cache_dr_{$_GET["arrowDataRequest"]}.php";
	    }elseif(isset($_GET["action"])){
	    	$file =  ARROW_CACHE_PATH."/models_cache/cache_a_{$_GET["action"]}.php";
	    }elseif(isset($_GET["template"]) ){
	    	$file =  ARROW_CACHE_PATH."/models_cache/cache_t_{$_GET["template"]}.php";
	    }else{
	      return array();
	    }
	    
		$includedModels = array();
		if(file_exists($file))
			require_once $file;
		return $includedModels;
	}
	
	public static function generateModelsCache($models, $paths){
		if(!SUPER_CACHE)
			return;
	    
		if(isset($_GET["action"])){
	      $fileName  =  ARROW_CACHE_PATH."/models_cache/cache_a_{$_GET["action"]}.php";      
	    }elseif(isset($_GET["arrowDataRequest"])){
	      $fileName =  ARROW_CACHE_PATH."/models_cache/cache_dr_{$_GET["arrowDataRequest"]}.php";
	    }elseif(isset($_GET["template"]) ){
	      $fileName =  ARROW_CACHE_PATH."/models_cache/cache_t_{$_GET["template"]}.php";
	    }else{
	      return;
	    }
		
		if(!file_exists($fileName)){
			
			$code = '$includedModels = array( '.self::array2string($models, true).');';
			
			if(count($models) != count($paths))
				return;
			
			foreach( $paths as $path ){
				$file = file_get_contents($path);
				$file = preg_replace( "/ArrowController *?:: *?importModel.+?\;/", "", $file );
				$file = str_replace("__FILE__", "'".$path."'",$file);
				$code.="\n".$file;
			}

			if(function_exists("token_get_all")){
				$tokens = token_get_all($code);
				$code = "";
				foreach ($tokens as $token) {
				   if (is_string($token)) {
				       // simple 1-character token
				       $code.=$token;
				   } else {
				       // token array
				       list($id, $text) = $token;
						
				       switch ($id) { 
				           case T_COMMENT: 
				           case T_OPEN_TAG:
				           case T_CLOSE_TAG:
				           default:
				               $code.=$text;
			               break;
				       }
				   }
				} 
			}else{
				$code = preg_replace("/<\?php[\r ]{0,}\n/ms", "",$code);
				$code = preg_replace("/[\r ]{0,}\n[ ]{0,}\?>/ms", "",$code);
			}
			file_put_contents($fileName, "<?php\n".$code."\n?>");
			if(self::$removeWhiteSpace)
				file_put_contents($fileName, php_strip_whitespace($fileName));
		}
	}
	
	
	
	public static function getFileCache( IArrowCacheable $object, $file, $handleParameters = array() ){
		
		$cacheFile = ARROW_CACHE_PATH."/".(isset($handleParameters["file_prefix"])?$handleParameters["file_prefix"]."_":"").md5( serialize( $file ) ).".php";		
		$generateCache = false;
		if( file_exists( $cacheFile ) ){
			if(!SUPER_CACHE){
				$cacheFileMTime = filemtime( $cacheFile );
				if( is_array($file) ){
					foreach( $file as $eFile ){
						if( $cacheFileMTime < filemtime($eFile) )
							$generateCache = true;
					}
				}else{
					if( $cacheFileMTime < filemtime($file) )
							$generateCache = true;
				}
			}
		}else{
			$generateCache = true;
		}
		
		if( $generateCache ){
			$result = call_user_func( array( $object, "generateCache" ), $handleParameters );
			if( is_array( $result ) ){
				$result  = self::array2File( $result, "cache" );
			}
			file_put_contents( $cacheFile, $result );
			file_put_contents( $cacheFile, php_strip_whitespace($cacheFile));
		}
		
		//print_r( "aaaa" );
		//exit;
		
		return $cacheFile;
	}
	
	public static function getCache( $sourceFile, $cacheHandle, $handleParameters = array() ){
		exit( $sourceFile );
	}


	public static function array2string($array, $indent = 0){
		$ret_str = "";
		$first = true;

		foreach ($array as $key => $value)
		{
			if (!$first)
			$ret_str .= ", \n";
			else
			$first = false;
			 
			$ret_str .= str_repeat(" ", $indent);
			$key = (is_int( $key ))?$key:"'{$key}'"; 
			
			if (is_array($value))
			{
				$ret_str .= "$key => array(\n".self::array2string($value, $indent+5)."\n".str_repeat(" ", $indent).")";
			}
			elseif (is_string($value))
			{
				$ret_str .= "$key => '$value'";
			}
			elseif (is_int($value))
			{
				$ret_str .= "$key => $value";
			}
			elseif (is_bool($value))
			{
				$ret_str .= "$key => ".($value?"true":"false");
			}
		}
		return $ret_str;
	}
	 
	private static function array2File($array, $name){ 
	    $file_str = "<?php\n $"."$name = array(\n"; 
	    $file_str .= self::array2string($array, 6);     
	    $file_str .= "\n );\n?>"; 
	    return $file_str;   
	}
}
?>